package com.yunji.aggregate.convert;

import com.alibaba.fastjson2.util.DateUtils;
import com.yunji.aggregate.cache.AggregateCache;
import com.yunji.aggregate.mapper.IContainerAggregateMapper;
import com.yunji.aggregate.model.dto.stock.StatisticsDataParam;
import com.yunji.aggregate.model.vo.container.CabinetTemplateCellVO;
import com.yunji.aggregate.model.vo.container.CabinetTemplateVO;
import com.yunji.common.enums.common.ErrorEnum;
import com.yunji.common.model.dto.LoginInfo;
import com.yunji.common.utils.TimeUtils;
import com.yunji.common.utils.bean.BeanUtils;
import com.yunji.system.context.SystemContext;
import org.springframework.util.Assert;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : peter-zhu
 * @date : 2024/12/10 11:30
 * @description : TODO
 **/
public class StatisticsDataConvert {

    public static void paramTime(StatisticsDataParam param) {
        String beginDay = param.getBeginDay();
        String closeDay = param.getCloseDay();
        //logs.info("【销售统计】 开始时间:{}, 结束时间:{}", beginDay, closeDay);
        Assert.isTrue(BeanUtils.isNotNull(beginDay), ErrorEnum.CHECKED_911002.getText());
        Assert.isTrue(BeanUtils.isNotNull(closeDay), ErrorEnum.CHECKED_911003.getText());

        LocalDate begin = DateUtils.parseLocalDate(param.getBeginDay());
        LocalDate close = DateUtils.parseLocalDate(param.getCloseDay());
        LocalDateTime min = TimeUtils.getMinDay(begin);
        LocalDateTime max = TimeUtils.getMaxDay(close);
        param.setMinTime(min);
        param.setMaxTime(max);
    }

    public static List<CabinetTemplateVO> handleProductPrice(List<CabinetTemplateVO> templates, IContainerAggregateMapper aggregateMapper) {
        List<CabinetTemplateVO> voList = new ArrayList<>();
        LoginInfo user = SystemContext.getUser();
        Long belongId = user.getBelongId();
        List<Long> templateIds = templates.stream().map(CabinetTemplateVO::getTemplateId).collect(Collectors.toList());
        List<CabinetTemplateCellVO> cells = aggregateMapper.searchCabinetTemplateCellList(belongId, templateIds);
        Map<Long, List<CabinetTemplateCellVO>> map = new HashMap<>();
        cells.forEach(cell -> map.computeIfAbsent(cell.getTemplateId(), k -> new ArrayList<>()).add(cell));
        templates.forEach(template -> {
            Long templateId = template.getTemplateId();
            if (!map.containsKey(templateId)) {
                return;
            }
            template.setTypeName(AggregateCache.getContainerTypeName(template.getTypeCode()));
            template.setList(map.get(templateId));
            CabinetTemplateVO vo = new CabinetTemplateVO();
            BeanUtils.clone(template, vo);
            voList.add(vo);
        });
        return voList;
    }

}
